package org.example.tmsapi.controller;

import org.example.tmsapi.model.Order;
import org.example.tmsapi.model.OrderLog;
import org.example.tmsapi.model.ResponseMessage;
import org.example.tmsapi.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/orders")
@CrossOrigin(origins = "*")
public class OrderController {
    
    @Autowired
    private OrderService orderService;
    
    // 获取订单详情
    @GetMapping("/{orderId}")
    public ResponseEntity<?> getOrderById(@PathVariable String orderId) {
        Order order = orderService.getOrderById(orderId);
        if (order == null) {
            return ResponseEntity.status(404).body(ResponseMessage.error("订单不存在"));
        }
        return ResponseEntity.ok(ResponseMessage.success(order));
    }
    
    // 搜索订单
    @GetMapping
    public ResponseEntity<?> searchOrders(
            @RequestParam(required = false) String orderNo,
            @RequestParam(required = false) String trackingNo,
            @RequestParam(required = false) String customerName) {
        List<Order> orders = orderService.searchOrders(orderNo, trackingNo, customerName);
        return ResponseEntity.ok(ResponseMessage.success(orders));
    }
    
    // 获取订单操作日志
    @GetMapping("/{orderId}/logs")
    public ResponseEntity<?> getOrderLogs(@PathVariable String orderId) {
        List<OrderLog> logs = orderService.getOrderLogs(orderId);
        return ResponseEntity.ok(ResponseMessage.success(logs));
    }
    
    // 更新订单状态
    @PutMapping("/{orderId}/status")
    public ResponseEntity<?> updateOrderStatus(@PathVariable String orderId, @RequestBody String newStatus) {
        // 获取当前登录用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String operator = authentication != null ? authentication.getName() : "系统";
        
        boolean success = orderService.updateOrderStatus(orderId, newStatus, operator);
        if (!success) {
            return ResponseEntity.status(404).body(ResponseMessage.error("订单不存在"));
        }
        return ResponseEntity.ok(ResponseMessage.success("订单状态更新成功"));
    }
    
    // 添加订单操作（演示用）
    @PostMapping("/{orderId}/operation")
    public ResponseEntity<?> addOrderOperation(@PathVariable String orderId, @RequestBody String operationContent) {
        // 获取当前登录用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String operator = authentication != null ? authentication.getName() : "系统";
        
        orderService.addOrderLog(orderId, operator, operationContent);
        return ResponseEntity.ok(ResponseMessage.success("操作记录添加成功"));
    }
}